﻿@page "/POSU8InvPrice"
@using System.Diagnostics.CodeAnalysis
@using BootstrapBlazor.OnlyServerZhongShun.Data.dbmodels
@using System.Data
@* @using MiniExcelLibs  *@
@inject AuthenticationStateProvider authenticationStateProvider
@inject ToastService ToastService
@inject IConfiguration _congifuration
@inject SqlSugarScope _SqlSugarScope
@attribute [Authorize(Roles = "超级管理员")]

<LinkButton Text="导出模板" Url="@herfexport" Target="_blank" />
<ButtonUpload TValue="string" IsMultiple="false" ShowProgress="true" OnChange="@OnClickToUpload" OnDelete="@(fileName => Task.FromResult(true))"></ButtonUpload>

<Table TItem="POS_U8_InvPrice"
       IsPagination="true" PageItemsSource="@PageItemsSource"
       IsStriped="true" IsBordered="true"
       ShowDefaultButtons="true"
       ShowToolbar="true" ShowDeleteButton="true"
       ClickToSelect="true" DoubleClickToEdit="true" ShowRefresh="false" ShowExportButton="true"
       OnQueryAsync="@OnQueryAsync" OnAddAsync="@OnAddAsync" OnDeleteAsync="@onDelete" OnSaveAsync="@OnSaveAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.u8Code" Width="180" />
        <TableColumn @bind-Field="@context.posName" Width="100" />
        <TableColumn @bind-Field="@context.u8Name" />
        <TableColumn @bind-Field="@context.item_size" />
        <TableColumn @bind-Field="@context.saleWeightPrice" />
        <TableColumn @bind-Field="@context.门店包装计量换算" />
    </TableColumns>
    <EditTemplate>
        <div class="row g-3">
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.u8Code" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.posName" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.u8Name" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.item_size" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.saleWeightPrice" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
            <div class="col-4">
                <BootstrapInput @bind-Value="@context.门店包装计量换算" placeholder="不可为空" maxlength="500">
                </BootstrapInput>
            </div>
        </div>
    </EditTemplate>
   
</Table>

@code {
    private static IEnumerable<int> PageItemsSource => new int[] { 10, 20, 40,100,1000 };

    private string herfexport = "Export/ExportBySql?tableName=POS_U8_InvPrice&sql=select u8Code, posName, u8Name, item_size, saleWeightPrice, 门店包装计量换算 from[POS_U8_InvPrice] where 1=2";
    private Task<QueryData<POS_U8_InvPrice>> OnQueryAsync(QueryPageOptions options)
    {
        IEnumerable<POS_U8_InvPrice> items = _SqlSugarScope.Queryable<POS_U8_InvPrice>().OrderBy(it => it.u8Code).ToList();

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<POS_U8_InvPrice>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = true,
                IsFiltered = true,
                IsSearch = true
            });
    }

    private static Task<POS_U8_InvPrice> OnAddAsync() => Task.FromResult(new POS_U8_InvPrice() { id = Guid.NewGuid() });

    private Task<bool> OnSaveAsync(POS_U8_InvPrice item, ItemChangedType changedType)
    {
        // 增加数据演示代码
        if (changedType == ItemChangedType.Add)
        {
            _SqlSugarScope.Insertable(item).ExecuteCommand();
        }
        else
        {
            _SqlSugarScope.Updateable(item).WhereColumns(it => it.id).ExecuteCommand();
        }
        return Task.FromResult(true);
    }

    private Task<bool> onDelete(IEnumerable<POS_U8_InvPrice> item)
    {
        // 增加数据演示代码
        _SqlSugarScope.Deleteable<POS_U8_InvPrice>(item).ExecuteCommand();

        return Task.FromResult(true);
    }
    private CancellationTokenSource? ReadToken { get; set; }
    bool ret = false;
    private async Task OnClickToUpload(UploadFile file)
    {
        if (file == null || file.OriginFileName == null)
        {
            return;
        }

        // Server Side 使用
        // Web Assembly 模式下必须使用 WebApi 方式去保存文件到服务器或者数据库中
        // 生成写入文件名称
        var ret = false;
        string path = Path.GetTempPath();
        if (!string.IsNullOrEmpty(path))
        {
            var uploaderFolder = Path.Combine(path, "POS_U8_InvPrice");
            file.FileName = $"{Path.GetFileNameWithoutExtension(file.OriginFileName)}-{DateTimeOffset.Now:yyyyMMddHHmmss}{Path.GetExtension(file.OriginFileName)}";
            var fileName = Path.Combine(uploaderFolder, DateTime.Now.ToFileTime() + file.FileName);

            ReadToken ??= new CancellationTokenSource();
            ret = await file.SaveToFileAsync(fileName, 5 * 1024 * 1024, ReadToken.Token);

            if (ret)
            {
                List<Data.dbmodels.POS_U8_InvPrice> data = MiniExcelLibs.MiniExcel.Query<Data.dbmodels.POS_U8_InvPrice>(fileName).ToList();
                //根据u8Code和posName，更新或者插入数据
                var x = _SqlSugarScope.Storageable(data)
                          .WhereColumns(it => new { it.u8Code,it.posName})//指定一个条件，当然支持多个 new {it.id,it.name}
                          .ToStorage();//将数据进行分组
                x.AsInsertable.ExecuteCommand(); //执行插入
                x.AsUpdateable.UpdateColumns(it => new { it.item_size, it.门店包装计量换算, it.saleWeightPrice }).ExecuteCommand();
                //刷新界面
                StateHasChanged();
               await ToastService.Information("上传文件", "成功");
            }
            else
            {
                var errorMessage = $"{"保存文件失败"} {file.OriginFileName}";
                file.Code = 1;
                file.Error = errorMessage;
                await ToastService.Error("上传文件", errorMessage);
            }
        }
    }
}
